import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, message, Select, InputNumber, TreeSelect, Modal, Tooltip, Spin } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { resourceUpdate, resourceDetail, resourceListTree } from '@/services/system/resource';
import * as Icons from '@ant-design/icons';
import { SearchOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import CustomPageContainer from '@/components/CustomPageContainer';
import { useCommonStyles } from '@/styles/commonStyles';

// 图标中文映射
const iconNameMap: Record<string, string> = {
  'UserOutlined': '用户',
  'TeamOutlined': '团队',
  'FileOutlined': '文件',
  'FolderOutlined': '文件夹',
  'DashboardOutlined': '仪表盘',
  'SettingOutlined': '设置',
  'MenuOutlined': '菜单',
  'AppstoreOutlined': '应用',
  'HomeOutlined': '首页',
  'SecurityScanOutlined': '安全',
  'SafetyCertificateOutlined': '认证',
  'KeyOutlined': '密钥',
  'ApiOutlined': '接口',
  'DatabaseOutlined': '数据库',
  'ClusterOutlined': '集群',
  'GroupOutlined': '分组',
  'UserSwitchOutlined': '切换用户',
  'SolutionOutlined': '解决方案',
  'AuditOutlined': '审计',
  'BarsOutlined': '列表',
  'OrderedListOutlined': '有序列表',
  'UnorderedListOutlined': '无序列表',
  'ProfileOutlined': '档案',
  'ProjectOutlined': '项目',
  'LogoutOutlined': '退出',
  'LoginOutlined': '登录',
};

interface TreeDataItem {
  id: string;
  resourceName: string;
  children?: TreeDataItem[];
  [key: string]: any;
}

interface TreeSelectNode {
  title: string;
  value: string;
  key: string;
  children?: TreeSelectNode[];
  isLeaf?: boolean;
}

// 获取所有图标
const allIcons = Object.keys(Icons)
  .filter(key => key.endsWith('Outlined'))
  .map(key => ({
    name: key,
    icon: Icons[key],
    label: iconNameMap[key] || key.replace('Outlined', ''),
  }));

// 定义图标选择器组件
const IconSelect: React.FC<{
  value?: string;
  onChange?: (value: string) => void;
}> = ({ value, onChange }) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedIcon, setSelectedIcon] = useState<string | undefined>(value);

  useEffect(() => {
    setSelectedIcon(value);
  }, [value]);

  const filteredIcons = allIcons.filter(icon =>
    icon.name.toLowerCase().includes(searchText.toLowerCase()) ||
    icon.label.includes(searchText)
  );

  const handleIconClick = (iconName: string) => {
    setSelectedIcon(iconName);
    onChange?.(iconName);
    setIsModalVisible(false);
  };

  const IconComponent = value && Icons[value] ? Icons[value] : SearchOutlined;

  return (
    <>
      <Input
        value={value ? `${iconNameMap[value] || value.replace('Outlined', '')} (${value})` : ''}
        readOnly
        placeholder="点击选择图标"
        onClick={() => setIsModalVisible(true)}
        prefix={<IconComponent />}
        style={{ cursor: 'pointer' }}
      />
      <Modal
        title="选择图标"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        width={800}
        footer={null}
      >
        <Input
          prefix={<SearchOutlined />}
          placeholder="搜索图标（支持中文）"
          value={searchText}
          onChange={e => setSearchText(e.target.value)}
          style={{ marginBottom: 16 }}
        />
        <div style={{
          height: '60vh',
          overflow: 'auto',
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(100px, 1fr))',
          gap: '8px',
        }}>
          {filteredIcons.map(({ name, icon: Icon, label }) => (
            <Tooltip title={`${label} (${name})`} key={name}>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  padding: '8px',
                  cursor: 'pointer',
                  border: selectedIcon === name ? '2px solid #1890ff' : '2px solid transparent',
                  borderRadius: '4px',
                  transition: 'all 0.3s',
                }}
                onClick={() => handleIconClick(name)}
              >
                <Icon style={{ fontSize: '24px' }} />
                <div style={{
                  fontSize: '12px',
                  marginTop: '4px',
                  width: '100%',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  textAlign: 'center',
                }}>
                  {label}
                </div>
              </div>
            </Tooltip>
          ))}
        </div>
      </Modal>
    </>
  );
};

const ResourceManageEdit: React.FC = () => {
  const { styles } = useCommonStyles();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const record = location.state?.record || {};
  const [treeData, setTreeData] = useState<TreeSelectNode[]>([]);
  const { institutionId, institutionRoleId, departmentId, positionId } = useModel('auth');

  useEffect(() => {
    const fetchResourceTree = async () => {
      try {
        setLoading(true);
        const params = {
          institutionId,
          institutionRoleId,
          departmentId,
          positionId,
        };
        const response = await resourceListTree(params);
        if (response.code === 200) {
          // 处理树形数据
          const processTreeData = (data: TreeDataItem[]): TreeSelectNode[] => {
            console.log('data', data);
            return data.map(item => ({
              title: item.resourceName,
              value: item.resourceId,
              key: item.resourceId,
              resourceParentId: item.resourceParentId,
              children: item.children ? processTreeData(item.children) : undefined,
              isLeaf: !item.children || item.children.length === 0,
            }));
          };

          const rootNode: TreeSelectNode = {
            title: '顶级资源',
            value: '0',
            key: '0',
            resourceParentId: '0',
            children: processTreeData(response.data),
          };
          setTreeData([rootNode]);
        } else {
          message.error(response.msg || '获取资源树失败');
        }
      } catch (error) {
        console.error('获取资源树失败:', error);
        message.error('获取资源树失败');
      } finally {
        setLoading(false);
      }
    };

    fetchResourceTree();
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      if (!record.resourceId) return;

      try {
        setLoading(true);
        const response = await resourceDetail({ resourceId: record.resourceId });
        if (response.code === 200) {
          const formData = {
            ...response.data,
            iconPath: response.data.iconPath || response.data.icon,
            // 如果上级资源为空，设置为顶级资源
            resourceParentId: response.data.resourceParentId || '0'
          };
          console.log('详情数据:', formData);
          form.setFieldsValue(formData);
        }
      } catch (error) {
        console.error('获取详情失败:', error);
        message.error('获取详情失败');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [record.resourceId]);

  const onFinish = async (values: any) => {
    console.log('提交的值:', values);
    try {
      setLoading(true);
      const requestData = {
        ...values,
        resourceId: record.resourceId,
        status: values.status ? 1 : 0,
        delFlag: 0,
        institutionId,
        institutionRoleId,
        departmentId,
        positionId,
        // 确保这些字段有值
        resourceName: values.resourceName?.trim(),
        alias: values.alias?.trim(),
        resourceParentId: values.resourceParentId || '0', // 如果上级资源为空，设置为顶级资源
        path: values.path?.trim(),
        resourceType: values.resourceType,
        iconPath: values.iconPath,
        sort: values.sort || 1,
        isOpen: values.isOpen || 0,
        visible: values.visible || 1,
      };

      console.log('提交的数据:', requestData);

      const response = await resourceUpdate(requestData);

      if (response.code === 200) {
        message.success('更新资源成功');
        navigate('/system/resourcemanage');
      } else {
        message.error(response.msg || '更新资源失败，请检查必填字段');
        console.error('提交失败，响应数据:', response);
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('更新资源失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  return (
    <CustomPageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <div className={styles.formContainer}>
            <div className={styles.title}>资源编辑</div>
            <Spin spinning={loading}>
              <Form
                form={form}
                layout="vertical"
                onFinish={onFinish}
                className={styles.form}
              >
                <div className={styles.formLayout}>
                  <Form.Item
                    name="resourceName"
                    label="资源名称"
                    rules={[{ required: true, message: '请输入资源名称' }]}
                    className={styles.formItem}
                  >
                    <Input placeholder="请输入资源名称" />
                  </Form.Item>

                  <Form.Item
                    name="alias"
                    label="资源别名"
                    rules={[{ required: true, message: '请输入资源别名' }]}
                    className={styles.formItem}
                  >
                    <Input placeholder="请输入资源别名，如：userManage" />
                  </Form.Item>

                  <Form.Item
                    name="resourceParentId"
                    label="上级资源"
                    rules={[{ required: true, message: '请选择上级资源' }]}
                    className={styles.formItem}
                  >
                    <TreeSelect
                      showSearch
                      style={{ width: '100%' }}
                      dropdownStyle={{
                        maxHeight: 400,
                        overflow: 'auto',
                        padding: '4px 0'
                      }}
                      placeholder="请选择上级资源"
                      allowClear
                      treeDefaultExpandAll
                      treeData={treeData}
                      treeNodeFilterProp="title"
                      showArrow
                      treeDefaultExpandedKeys={['0']}
                      notFoundContent="暂无数据"
                      className={styles.treeSelect}
                      fieldNames={{
                        label: 'title',
                        value: 'value',
                        children: 'children'
                      }}
                      onSelect={(value, node: any) => {
                        console.log('选中的节点:', node);
                        form.setFieldsValue({
                          resourceParentId: value || '0' // 如果值为空，设置为顶级资源
                        });
                      }}
                      onChange={(value) => {
                        if (!value) {
                          form.setFieldsValue({
                            resourceParentId: '0' // 清空时设置为顶级资源
                          });
                        }
                      }}
                    />
                  </Form.Item>

                  <Form.Item
                    name="path"
                    label="路由地址"
                    rules={[{ required: true, message: '请输入路由地址' }]}
                    className={styles.formItem}
                  >
                    <Input placeholder="请输入路由地址，如：/sys/user" />
                  </Form.Item>

                  <Form.Item
                    name="resourceType"
                    label="资源类型"
                    rules={[{ required: true, message: '请选择资源类型' }]}
                    className={styles.formItem}
                  >
                    <Select placeholder="请选择资源类型">
                      <Select.Option value="menu">菜单</Select.Option>
                      <Select.Option value="page">页面</Select.Option>
                      <Select.Option value="button">按钮</Select.Option>
                      <Select.Option value="api">接口</Select.Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="action"
                    label="操作按钮类型"
                    className={styles.formItem}
                  >
                    <Select placeholder="请选择操作按钮类型">
                      <Select.Option value="add">新增</Select.Option>
                      <Select.Option value="edit">编辑</Select.Option>
                      <Select.Option value="delete">删除</Select.Option>
                      <Select.Option value="view">查看</Select.Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="iconPath"
                    label="资源图标"
                    rules={[{ required: true, message: '请选择资源图标' }]}
                    className={styles.formItem}
                  >
                    <IconSelect />
                  </Form.Item>

                  <Form.Item
                    name="sort"
                    label="排序"
                    rules={[{ required: true, message: '请输入排序号' }]}
                    className={styles.formItem}
                  >
                    <InputNumber
                      min={1}
                      max={999}
                      style={{ width: '100%' }}
                      placeholder="请输入排序号，数值越小越靠前"
                    />
                  </Form.Item>

                  <Form.Item
                    name="isOpen"
                    label="是否打开新页面"
                    rules={[{ required: true, message: '请选择是否打开新页面' }]}
                    className={styles.formItem}
                  >
                    <Select placeholder="请选择是否打开新页面">
                      <Select.Option value={1}>是</Select.Option>
                      <Select.Option value={0}>否</Select.Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="visible"
                    label="是否显示"
                    rules={[{ required: true, message: '请选择是否显示' }]}
                    className={styles.formItem}
                  >
                    <Select placeholder="请选择是否显示">
                      <Select.Option value={1}>显示</Select.Option>
                      <Select.Option value={0}>隐藏</Select.Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="remark"
                    label="资源备注"
                    className={`${styles.formItem} ${styles.fullWidth}`}
                  >
                    <Input.TextArea rows={4} placeholder="请输入资源备注" />
                  </Form.Item>
                </div>

                <div className={styles.buttonGroup}>
                  <Button onClick={() => navigate('/system/resourcemanage')}>
                    返回
                  </Button>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    确定
                  </Button>
                </div>
              </Form>
            </Spin>
          </div>
        </Card>
      </div>
    </CustomPageContainer>
  );
};

export default ResourceManageEdit;
